<?php

namespace App\Services\Permission;

use App\Models\Permission;
use App\Models\Site;
use ModuleService;
use App\Models\Module;
use Spatie\Permission\Models\Permission as ModelsPermission;

/**
 * 权限
 * @package App\Services
 */
class PermissionService
{
    /**
     * 更新站点权限
     *
     * @param Site $site
     * @return void
     */
    public function updateSitePermission(Site $site)
    {
        $modules = ModuleService::getSiteModules($site);
        foreach ($modules as $module) {
            $permissons = ModuleService::config($module['name'], 'permissions');
            foreach ($permissons as $permisson) {
                foreach ($permisson['rules'] as $rule) {
                    $name = $this->permissionName($site, $module, $rule['name']);
                    ModelsPermission::updateOrCreate([
                        'name' => $name
                    ], ['name' => $name, 'title' => $rule['title']]);
                }
            }
        }
    }

    public function permissionName(Site $site, Module $module, $name)
    {
        return "S{$site['id']}-{$module['name']}-$name";
    }
}
